package com.fa.ojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.FoundWord;
import cn.hutool.dfa.WordTree;
import com.fa.ojcodesandbox.model.ExecuteCodeRequest;
import com.fa.ojcodesandbox.model.ExecuteCodeResponse;
import com.fa.ojcodesandbox.model.ExecuteMessage;
import com.fa.ojcodesandbox.model.JudgeInfo;
import com.fa.ojcodesandbox.utils.ProcessUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * ClassName: JavaNativeCodeSandbox
 * Package: com.fa.ojcodesandbox
 * Description:
 *
 * @Author:
 * @Create: 2024/4/27 - 10:28
 * @Version: v1.0
 */
public class JavaNativeCodeSandboxOld implements CodeSandbox{

    private static final String GLOBAL_CODE_DIR_NAME = "tempCode";

    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    //安全管理类的全路径
    private static final String SECURITY_MANAGER_CLASS_PATH = "D:\\after-code\\oj-code-sandbox\\src\\main\\resources\\security";

    // 安全管理类
    private static final String SECURITY_MANAGER_CLASS_NAME = "MySecurityManager";

    //设置超时时间，防止用户恶意长时间占用资源
    private static final long TIME_OUT = 100000;

    //定义一个黑名单，用于限制用户的操作
    private static final List<String> BLACK_LIST = Arrays.asList("Files","exec","rm", "rm -rf", "rm -r", "rm -R", "rm -d", "rm -D");

    // wordTree用于校验代码中是否含有敏感字符
    private static final WordTree WORD_TREE;

    static {
        // 初始化字典树
        WORD_TREE = new WordTree();
        WORD_TREE.addWords(BLACK_LIST);
    }

    public static void main(String[] args) {
        JavaNativeCodeSandbox javaNativeCodeSandbox = new JavaNativeCodeSandbox();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        executeCodeRequest.setLanguage("java");
        executeCodeRequest.setInputList(Arrays.asList("1 2", "1 3"));
        String code = ResourceUtil.readStr("testCode/Main.java", StandardCharsets.UTF_8);
        executeCodeRequest.setCode(code);

        ExecuteCodeResponse executeCodeResponse = javaNativeCodeSandbox.executeCode(executeCodeRequest);
        System.out.println("executeCodeResponse = " + executeCodeResponse);
    }

    /**
     * 1. 把用户的代码保存为.java文件
     * 2. 将 .java文件编译为 .class文件
     * 3. 执行代码，得到输出结果
     * 4. 收集整理输出结果
     * 5. 文件清理
     * 6. 错误处理，提升程序的健壮性
     * @param executeCodeRequest
     * @return
     */
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();

        // 校验用户传入的代码，是否包含敏感词汇
        /* 优化：将这两行代码放到静态代码块中，当类加载是只需要创建一次
        WordTree wordTree = new WordTree();
        wordTree.addWords(BLACK_LIST);*/
        FoundWord foundWord = WORD_TREE.matchWord(code);
        if (foundWord != null && foundWord.length() > 0) {
            System.out.println("foundWord = " + foundWord);
            //foundWord，找的单词长度大于0 说明代码中存在黑名单中的单词
            return getErrorResponse("代码中包含敏感词汇");
        }

        // 这里得到的是项目的 全路径
        String userDir = System.getProperty("user.dir");
        // 这里使用 File.separator 作为分隔符而不用 /，是为了兼容 Linux、mac
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        // 判断全局代码目录是否存在，不存在则创建
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }

        // 1.把用户的代码隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodeFileFullPath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodeFileFullPath, StandardCharsets.UTF_8);
        // 2. 编译.java文件， 得到.class文件
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            ExecuteMessage compileExecuteMessage = ProcessUtils.getRunProcessResult(compileProcess, "编译");
            System.out.println("compileExecuteMessage = " + compileExecuteMessage);
        } catch (IOException e) {
            return getErrorResponse(e);
        }

        // 3. 执行 编译好的 .class文件，得到输出结果
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        // maxRunTime只存 程序用时最长的； 在判题服务中只要有一个值超过限制时间，就说明答案不正确
        long maxRunTime = 0;
        for (String inputArgs : inputList) {
            // 在执行程序时，限制资源分配。防止用户占用内存
//            String executeCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeParentPath, inputArgs);
            //直接在指令上指定安全管理器
            String executeCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s;%s -Djava.security.manager=%s Main %s", userCodeParentPath, SECURITY_MANAGER_CLASS_PATH, SECURITY_MANAGER_CLASS_NAME, inputArgs);
            try {
                // 在执行用户传入的代码时，使用java安全管理器
                //System.setSecurityManager(new MySecurityManager());在这里指定安全管理器会浪费很多资源
                // Runtime.getRuntime()是开启新的子进程
                Process executeProcess = Runtime.getRuntime().exec(executeCmd);
                // 超时控制。开启新线程，防止恶意代码恶意占用程序
                new Thread(() -> {
                    try {
                        Thread.sleep(TIME_OUT);
                        // 线程睡醒了，就 判断进程是否还在执行，若还在执行则 销毁 开启的子进程
                        if (executeProcess.isAlive()) {
                            executeProcess.destroy();
                            System.out.println("超时了，中断");
                        }
                    } catch (InterruptedException e) {
                       throw new RuntimeException(e);
                    }
                }).start();
                ExecuteMessage runExecuteMessage = ProcessUtils.getRunProcessResult(executeProcess, "执行");
                // 将每次的执行信息添加到 executeMessageList
                executeMessageList.add(runExecuteMessage);
                Long actualTime = runExecuteMessage.getTime();
                if (actualTime != null) {
                    maxRunTime = Math.max(maxRunTime, actualTime);
                }
                // 输出每次的执行信息
                System.out.println("runExecuteMessage = " + runExecuteMessage);
            } catch (IOException e) {
                return getErrorResponse(e);
            }
        }
        
        //4. 收集、整理输出结果
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        //定义 successOutputList 用于接收执行成功的输出
        List<String> successOutputList = new ArrayList<>();
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                //错误信息不为 空，说明执行失败
                executeCodeResponse.setMessage(errorMessage);
                // 执行中存在错误
                executeCodeResponse.setStatus(3);
                break;
            }
            // 错误信息为空说明，执行成功
            successOutputList.add(executeMessage.getMessage());
        }
        if (successOutputList.size() == executeMessageList.size()) {
            // 如果成功执行的输出的size和执行消息的size大小相同，说明正常运行完成
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutputList(successOutputList);
        JudgeInfo judgeInfo = new JudgeInfo();
//        judgeInfo.setMessage();
        // todo 获取程序内存未实现
//        judgeInfo.setMemory();
        judgeInfo.setTime(maxRunTime);
        executeCodeResponse.setJudgeInfo(judgeInfo);

        // 5. 文件清理
        if (FileUtil.exist(userCodeParentPath)) {
            boolean del = FileUtil.del(userCodeParentPath);
            System.out.println(del ? "目录删除成功" : "目录删除失败");
        }
        return executeCodeResponse;
        // 6. 错误处理，提升程序健壮性
    }


    /**
     * 获取错误响应
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        // 表示代码沙箱错误
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setMessage(e.getMessage());
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }

    /**
     * 获取错误响应
     * @param errorMessage
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(String errorMessage) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        // 表示代码沙箱错误
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setMessage(errorMessage);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }
}
